package com.mall.shopping.services;

import com.mall.commons.tool.exception.ProcessException;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.CartItemConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import com.mall.shopping.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.Redisson;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @Name : ICartServiceImpl.java
 * @Time : 2021/8/25 23:45
 * @Author : creamycandy
 * @Software : IntelliJ IDEA
 */
@Service
@Slf4j
public class ICartServiceImpl implements ICartService {

    @Autowired
    ItemMapper itemMapper;

    //1.new 一个config
    Config config = new Config();
    //2.配置config对象
    SingleServerConfig singleServerConfig = config.useSingleServer().
            setAddress("redis://localhost:6379");
    //3.创建redis客户端
    RedissonClient redissonClient = Redisson.create(config);
    //用hash数据结构
    RMap<Long, List<CartProductDto>> cart = redissonClient.getMap("Cart");

    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse response = new CartListByIdResponse();
        try {
            request.requestCheck();
            List<CartProductDto> cartProductDtos = cart.get(request.getUserId());
            response.setCartProductDtos(cartProductDtos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (ValidateException e) {
            log.error("ICartServiceImpl.getCartListById occur ValidateException :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        } catch (Exception e) {
            log.error("ICartServiceImpl.getCartListById occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse response = new AddCartResponse();
        try {
            request.requestCheck();
            List<CartProductDto> cartProductDtos = cart.get(request.getUserId());
            if(cartProductDtos!=null){
                for (CartProductDto productDto : cartProductDtos) {
                    if (productDto.getProductId().equals(request.getItemId())) {
                        productDto.setProductNum(productDto.getProductNum() + request.getNum());
                        if (productDto.getProductNum() > productDto.getLimitNum()) {
                            throw new ProcessException();
                        }
                        cart.put(request.getUserId(), cartProductDtos);
                        response.setCode(ShoppingRetCode.SUCCESS.getCode());
                        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
                        return response;
                    }
                }
            }
            if(cartProductDtos == null){
                List<CartProductDto> carts = new ArrayList<>();
                cartProductDtos = carts;
            }
            Item item = itemMapper.selectByPrimaryKey(request.getItemId());
            CartProductDto cartProductDto = CartItemConverter.item2Dto(item);
            Long num = Long.valueOf(request.getNum());
            if (num > cartProductDto.getLimitNum()) {
                throw new ProcessException();
            }
            cartProductDto.setProductNum(num);
            cartProductDtos.add(cartProductDto);
            cart.put(request.getUserId(), cartProductDtos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (ValidateException e) {
            log.error("ICartServiceImpl.addToCart occur ValidateException :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        } catch (ProcessException e) {
            log.error("ICartServiceImpl.addToCart occur ProcessException :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            response.setMsg("商品超出可购买购物车数量");
        } catch (Exception e) {
            log.error("ICartServiceImpl.addToCart occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        try {
            request.requestCheck();
            List<CartProductDto> cartProductDtos = cart.get(request.getUserId());
            for (CartProductDto cartProductDto : cartProductDtos) {
                if (cartProductDto.getProductId().equals(request.getItemId())) {
                    if (request.getNum() > cartProductDto.getLimitNum()) {
                        throw new ProcessException();
                    }
                    cartProductDto.setChecked(request.getChecked());
                    cartProductDto.setProductNum(Long.valueOf(request.getNum()));
                }
            }
            cart.put(request.getUserId(), cartProductDtos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (ValidateException e) {
            log.error("ICartServiceImpl.updateCartNum occur ValidateException :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        } catch (ProcessException e) {
            log.error("ICartServiceImpl.updateCartNum occur ProcessException :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            response.setMsg("商品超出可购买购物车数量");
        } catch (Exception e) {
            log.error("ICartServiceImpl.updateCartNum occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse response = new CheckAllItemResponse();
        try {
            request.requestCheck();
            List<CartProductDto> cartProductDtos = cart.get(request.getUserId());
            for (CartProductDto cartProductDto : cartProductDtos) {
                cartProductDto.setChecked(request.getChecked());
            }
            cart.put(request.getUserId(), cartProductDtos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (ValidateException e) {
            log.error("ICartServiceImpl.checkAllCartItem occur ValidateException :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        } catch (Exception e) {
            log.error("ICartServiceImpl.checkAllCartItem occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse response = new DeleteCartItemResponse();
        try {
            request.requestCheck();
            List<CartProductDto> cartProductDtos = cart.get(request.getUserId());
            for (CartProductDto cartProductDto : cartProductDtos) {
                if (cartProductDto.getProductId().equals(request.getItemId())) {
                    cartProductDtos.remove(cartProductDto);
                    break;
                }
            }
            cart.put(request.getUserId(), cartProductDtos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (ValidateException e) {
            log.error("ICartServiceImpl.deleteCartItem occur ValidateException :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        } catch (Exception e) {
            log.error("ICartServiceImpl.deleteCartItem occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();
        try {
            request.requestCheck();
            List<CartProductDto> cartProductDtos = cart.get(request.getUserId());
            Integer size = cartProductDtos.size();
            for (int i = 0; i < size; i++) {
                if ("true".equals(cartProductDtos.get(i).getChecked())) {
                    cartProductDtos.remove(cartProductDtos.get(i));
                    i = -1;
                    size = cartProductDtos.size();
                }
            }
            cart.put(request.getUserId(), cartProductDtos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (ValidateException e) {
            log.error("ICartServiceImpl.deleteCheckedItem occur ValidateException :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        } catch (Exception e) {
            log.error("ICartServiceImpl.deleteCheckedItem occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        ClearCartItemResponse response = new ClearCartItemResponse();
        try {
            request.requestCheck();
            List<CartProductDto> cartProductDtos = cart.get(request.getUserId());
            Integer size = cartProductDtos.size();
            for (int i = 0; i < size; i++) {
                if (request.getProductIds().contains(cartProductDtos.get(i).getProductId())) {
                    cartProductDtos.remove(cartProductDtos.get(i));
                    size = cartProductDtos.size();
                    i = -1;
                }
            }
            cart.put(request.getUserId(), cartProductDtos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (ValidateException e) {
            log.error("ICartServiceImpl.clearCartItemByUserID occur ValidateException :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        } catch (Exception e) {
            log.error("ICartServiceImpl.clearCartItemByUserID occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }
}

